package com.xinyue.game.auth;

import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.*;

import java.time.Duration;
import java.util.Date;

public class JWTUtil {
    private final static String TOKEN_SECRET = "game_token#$%Abc";

    public static String createToken(ITokenParams tokenContent) {
        if (tokenContent == null) {
            throw new IllegalArgumentException("token参数不能为空");
        }
        if (tokenContent.expireDays() <= 0) {
            throw new IllegalArgumentException("expire必须大于0");
        }
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;//使用对称加密算法生成签名
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        String subject = JSON.toJSONString(tokenContent);
        JwtBuilder builder = Jwts.builder().setId(String.valueOf(nowMillis)).setIssuedAt(now).setSubject(subject).signWith(signatureAlgorithm, TOKEN_SECRET);
        long expMillis = nowMillis + Duration.ofDays(tokenContent.expireDays()).toMillis();
        Date exp = new Date(expMillis);
        builder.setExpiration(exp);
        return builder.compact();
    }

    public static <T> T getTokenContent(String token, Class<T> clazz) throws TokenException {
        try {
            Claims claims = Jwts.parser().setSigningKey(TOKEN_SECRET).parseClaimsJws(token).getBody();
            String subject = claims.getSubject();
            T tokenBody = JSON.parseObject(subject, clazz);
            return tokenBody;
        } catch (Throwable e) {
            TokenException exp = new TokenException("token解析失败", e);
            if (e instanceof ExpiredJwtException) {
                exp.setExpire(true);
            }
            throw exp;
        }
    }

}
